<?php

App::uses('AuthComponent', 'Controller/Component');

class Usuarios extends appModel {

    public $name = 'Usuario';
    public $displayField = 'usuario';
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'Laboratorio' => array(
            'className' => 'Laboratorio',
            'foreignKey' => 'laboratorio_id'
    ));

//    public function beforeSave($options = array()) {
//        if (isset($this->data[$this->alias]['password'])) {
//            $passwordHasher = new SimplePasswordHasher();
//            $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
//        }
//        return true;
//    }
//    public $belongsTo = array('Laboratorio');
    public function beforeSave($options = array()) {
        if (isset($this->data[$this->name]['senha']) && !empty($this->data[$this->name]['senha'])) {
            $this->data[$this->name]['senha'] = AuthComponent::password($this->data[$this->name]['senha']);
        }
        return true;
    }

    public $validate = array(
        'usuario' => array(
            array(
                'rule' => array('notEmpty'),
                'message' => 'Nome de usuário obrigatório'
            ),
            array(
                'rule' => 'isUnique',
                'message' => 'Este usuário já existe'
            )
        ),
        'email' => array(
            array(
                'rule' => array('email'),
                'message' => 'Email inválido'
            )
        ),
        'senha' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'Senha obrigatória',
                'on' => 'create'
            )
        ),
        'cargo' => array(
            'valid' => array(
                'rule' => array('inList', array('admin', 'funcionario')),
                'message' => 'Entre com um cargo válido',
                'allowEmpty' => false
            )
        )
    );

//    public function beforeSave($options = array()) {
//        if (isset($this->data[$this->alias]['senha'])) {
//            $this->data[$this->alias]['senha'] = AuthComponent::password($this->data[$this->alias]['senha']);
//        }
//        return true;
//    }
    public function isEqual($user_, $user) { //verifica se
        return $this->field('id', array('id' => $user_, 'id' => $user)) === $user_;
    }

    public function generateHashChangePassword() {
        $salt = Configure::read('Security.salt');
        $salt_v2 = Configure::read('Security.cipherSeed');
        $rand = mt_rand(1, 999999999);
        $rand_v2 = mt_rand(1, 999999999);

        $hash = hash('sha256', $salt . $rand . $salt_v2 . $rand_v2);

        return $hash;
    }

}

?>